import * as Yup from 'yup'
import { Formik, Form, Field, ErrorMessage, useField } from 'formik'

function MyInputField ({ label, ...props }) {
  const [field, meta] = useField(props)
  return <div>
    <label htmlFor={props.id}>{label}</label>
    <input {...field} {...props} />
    <span>{ meta.touched && meta.error ? meta.error: null }</span>
  </div>
}

function Checkbox ({ label, ...props }) {
  const [field, meta, helper] = useField(props)
  const {value} = meta
  const { setValue } = helper
  const handleChange = () => {
    const set = new Set(value)
    if (set.has(props.value)) {
      set.delete(props.value)
    } else {
      set.add(props.value)
    }
    setValue([...set])
  }
  return <div>
    <label htmlFor="" >
      <input checked={value.includes(props.value)} type="checkbox" {...props} onChange={handleChange} />{label}
    </label>
  </div>
}

export default function App () {

  const initialValues = {
    username: '张三',
    content: '我是内容',
    subject: 'java',
    hobbies: ['足球', '篮球']
  }
  const handleSubmit = values => {
    console.log(values)
  }
  const schema = Yup.object({
    username: Yup.string().max(15, '用户名的长度不能大于15').required('请输入用户名'),
    password: Yup.string().min(6, '密码的长度不能小于6').required('请输入密码'),
  })
  return (
    <Formik
      initialValues={initialValues}
      onSubmit={handleSubmit}
      validationSchema={schema}
    >
      <Form>
        <Field name="username" />
        <ErrorMessage name="username" />
        <Field as="textarea" name="content" />
        <Field as="select" name="subject" >
          <option value="java">java</option>
          <option value="js">js</option>
        </Field>
        <MyInputField id="myPass" label="密码" type="password" name="password" placeholder="请输入密码" />
        <Checkbox value="足球" label="足球" name="hobbies" />
        <Checkbox value="篮球" label="篮球" name="hobbies" />
        <Checkbox value="橄榄球" label="橄榄球" name="hobbies" />
        <button type="submit">提交</button>
      </Form>
    </Formik>
  )
}